package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Storage;
import com.ywgt.service.AliossService;
import com.ywgt.service.StorageService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin/storage")
@ApiModel("存储管理")
public class StorageController {

    @Autowired
    AliossService aliossService;

    @Autowired
    StorageService storageService;

    @PostMapping("/create")
    public Object create(MultipartFile file){
        String url = aliossService.upload(file);
        if(storageService.create(url,file)){
            Map<String,Object> data=new HashMap<>();
            data.put("url",url);
            return ResponseUtil.ok(data);
        }
        return ResponseUtil.fail();
    }

    /**
     * page: 1,
     *         limit: 20,
     *         key: undefined,
     *         name: undefined,
     *         sort: 'add_time',
     *         order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getOss(String name,String key, @RequestParam(required = false,defaultValue = "add_time") String sort,
                         @RequestParam(required = false,defaultValue = "desc") String order,
                         @RequestParam(required = false,defaultValue = "1") int page,
                         @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Storage> storages=storageService.getStorages(name,key,page,limit,sort,order);
        List<Storage> items = storages.getResult();
        long total = storages.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("items",items);
        data.put("total",total);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Storage storage){
        if(storageService.removeById(storage.getId())){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/update")
    public Object update(@RequestBody Storage storage){
        if(storageService.updateById(storage)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
}
